﻿Imports Telerik.Windows.Controls
Imports Telerik.Windows.Data
Imports CRM.BusinessLayer
Imports System.Data
Imports System.Text
Partial Public Class frmAdminTaskTemplates

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub frmAdminTaskTemplates_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        GeneralTasks.ChangeTheme(Me)
        GeneralTasks.EnumerateandFill(Me.LogicalChildren)
        RefreshList()
        Me.txtName.IsEnabled = False
        Me.txtType.IsEnabled = False
        Me.txtWorkingDays.IsEnabled = False
        Me.txtMessage.IsEnabled = False
    End Sub

    Private Sub RefreshList()
        Dim StrSQL As String, templateList As DataTable
        StrSQL = "Select TaskTemplate_ID as ID, TaskTemplate_Name as Name from D_TaskTemplates Order By TaskTemplate_ID"
        templateList = CommonDataFunctions.GetSQLDatatable(StrSQL)
        grdTemplates.ItemsSource = templateList
        grdTemplates.Columns("ID").Width = New GridLength(60)
        grdTemplates.Columns(1).Width = New GridLength(150)
    End Sub

    Private Function GetTaskTemplateList(ByVal TaskTemplate_ID As Integer) As DataTable
        Dim StrSQL As String, templateList As DataTable
        StrSQL = "Select TaskTemplate_ID as ID,TaskTemplate_Name as Name,TaskTemplate_Type as Type,TaskTemplate_Message as Message,TaskTemplate_WorkingDays as Days  from D_TaskTemplates where TaskTemplate_ID=" & TaskTemplate_ID
        templateList = CommonDataFunctions.GetSQLDatatable(StrSQL)
        Return templateList
    End Function

    Private Sub grdTemplates_SelectionChanged(ByVal sender As Object, ByVal e As Telerik.Windows.Controls.SelectionChangeEventArgs) Handles grdTemplates.SelectionChanged
        Me.txtName.IsEnabled = True
        Me.txtType.IsEnabled = True
        Me.txtWorkingDays.IsEnabled = True
        Me.txtMessage.IsEnabled = True
        Me.btnInsertBookmark.IsEnabled = False
        Me.btnCancel.IsEnabled = False
        Me.grdBookMarks.IsEnabled = False
    End Sub

    Private Sub btnDeleteTemplate_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDeleteTemplate.Click

        Dim StrSQL As String, Result As DataTable, StrMess As String
        Dim selectedTemplateRow As DataRow = Me.grdTemplates.SelectedItem
        If selectedTemplateRow Is Nothing Then
            MsgBox("Select the Template to delete.")
            Exit Sub
        End If
        StrSQL = "Select Automation_ID from D_Automation "
        StrSQL = StrSQL & " Where Automation_JobType = 1"
        StrSQL = StrSQL & " And Automation_LinkID = " & selectedTemplateRow(0)

        Result = CommonDataFunctions.GetSQLDatatable(StrSQL)

        If Result.Rows.Count > 0 Then
            Result.Dispose()
            Call MsgBox("This template is currently in use in the Automation system, please remove it from any active jobs before deleting", , "Error")
            Exit Sub
        End If
        Result.Dispose()

        StrSQL = "Delete From D_TaskTemplates where TaskTemplate_ID = " & selectedTemplateRow(0)
        StrMess = "Task Template number " & selectedTemplateRow(0) & " (" & selectedTemplateRow(1) & ") deleted"

        If CommonDataFunctions.ExecuteSQL(StrSQL) = True Then
            Me.txtMessage.Text = String.Empty
            Me.txtName.Text = String.Empty
            Me.txtType.Text = String.Empty
            Me.txtWorkingDays.Text = String.Empty
            RefreshList()
            MsgBox(StrMess)
        Else
            MsgBox("There is an error while Deleting Task Template into the system. Please try again or contact IT", MsgBoxStyle.Critical, "Unsuccessful")
            Exit Sub
        End If

    End Sub

    Private Sub btnAddNewTemplate_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddNewTemplate.Click
        If btnAddNewTemplate.Content.ToString.ToUpper = "ADD NEW TEMPLATE" Then
            Me.txtMessage.Text = String.Empty
            Me.txtName.Text = String.Empty
            Me.txtType.Text = String.Empty
            Me.txtWorkingDays.Text = String.Empty
            Me.txtName.IsEnabled = True
            Me.txtType.IsEnabled = True
            Me.txtWorkingDays.IsEnabled = True
            Me.txtMessage.IsEnabled = True
            Me.btnAddNewTemplate.Content = "Save"
            Me.grdBookMarks.IsEnabled = True
            Me.btnInsertBookmark.IsEnabled = True
            Me.btnEditTemplate.IsEnabled = False
            Me.btnDeleteTemplate.IsEnabled = True
            Me.btnCancel.IsEnabled = True
            Me.txtName.Focus()
            FillBookMarkList()

            Me.txtWorkingDays.Text = String.Empty
            Me.txtWorkingDays.IsEnabled = True


            Me.txtMessage.Text = String.Empty
            Me.txtMessage.IsEnabled = True


            Me.txtName.Text = String.Empty
            Me.txtName.IsEnabled = True


            Me.txtType.Text = String.Empty
            Me.txtType.IsEnabled = True

            Me.grdTemplates.IsEnabled = False
            FillBookMarkList()
            Me.grdBookMarks.IsEnabled = True
            Me.btnInsertBookmark.IsEnabled = True
            Me.Txt_CursorPosition.Text = 0


            Me.btnEditTemplate.IsEnabled = False
            Me.btnCancel.IsEnabled = True
        ElseIf Me.btnAddNewTemplate.Content.ToString.ToUpper = "SAVE" Then
            Dim StrSQL As String, Result As DataTable, StrMess As String
            If Me.txtName.Text = String.Empty Then
                Call MsgBox("Name cannot be blank", , "Error")
                Me.txtName.Focus()
                Exit Sub
            End If

            If Len(Me.txtName.Text) > 50 Then
                Call MsgBox("Name too long (Max 50 chars)", , "Error")
                Me.txtName.Focus()
                Exit Sub
            End If

            If Me.txtType.Text = String.Empty Then
                Call MsgBox("Type cannot be blank", , "Error")
                Me.txtType.Focus()
                Exit Sub
            End If

            If Len(Me.txtType.Text) > 50 Then
                Call MsgBox("Type too long (Max 100 chars)", , "Error")
                Me.txtType.Focus()
                Exit Sub
            End If

            If Me.txtMessage.Text = String.Empty Then
                Call MsgBox("Message cannot be blank", , "Error")
                Me.txtMessage.Focus()
                Exit Sub
            End If

            If Me.txtWorkingDays.Text = String.Empty Then
                Call MsgBox("Working Days ahead cannot be blank", , "Error")
                Me.txtWorkingDays.Focus()
                Exit Sub
            End If

            If Not IsNumeric(Me.txtWorkingDays.Text) Then
                Call MsgBox("Invalid value for Working Days ahead", , "Error")
                Me.txtWorkingDays.Focus()
                Exit Sub
            End If

            If CInt(Me.txtWorkingDays.Text) < 0 Or CInt(Me.txtWorkingDays.Text) > 1200 Then
                Call MsgBox("Invalid value for Working Days ahead (0-1200 days)", , "Error")
                Me.txtWorkingDays.Focus()
                Exit Sub
            End If

            StrSQL = "Select TaskTemplate_ID from D_TaskTemplates"
            StrSQL = StrSQL & " Where TaskTemplate_Name = '" & Me.txtName.Text & "'"

            Result = CommonDataFunctions.GetSQLDatatable(StrSQL)
            If Result.Rows.Count > 0 Then
                Result.Dispose()
                Call MsgBox("There is already a template with that name", , "Error")
                Exit Sub
            End If

            StrSQL = "Insert into D_TaskTemplates"
            StrSQL = StrSQL & " ( TaskTemplate_Name, TaskTemplate_Type, TaskTemplate_Message, TaskTemplate_WorkingDays, TaskTemplate_EnteredBy)"
            StrSQL = StrSQL & " VALUES("
            StrSQL = StrSQL & " '" & Me.txtName.Text & "', "
            StrSQL = StrSQL & " '" & Me.txtType.Text & "', "
            StrSQL = StrSQL & " '" & Me.txtMessage.Text & "', "
            StrSQL = StrSQL & CInt(Me.txtWorkingDays.Text) & ", "
            StrSQL = StrSQL & "'" & GlobalCRM.CurrentConName & "')"

            If CommonDataFunctions.ExecuteSQL(StrSQL) = False Then
                MsgBox("There is an error while entering New Task Template into the system. Please try again or contact IT", MsgBoxStyle.Critical, "Unsuccessful")
                Exit Sub
            End If


            StrSQL = "Select TaskTemplate_ID from D_TaskTemplates where TaskTemplate_Name = '" & Me.txtName.Text & "'"
            Result = CommonDataFunctions.GetSQLDatatable(StrSQL)

            If Result.Rows.Count = 0 Then
                Result.Dispose()
                Call MsgBox("New template not found", , "Error")
                Exit Sub
            End If

            StrMess = "New Task Template added" & vbCrLf
            StrMess = StrMess & vbCrLf & "ID         :" & Result(0)("TaskTemplate_ID")
            Result.Dispose()

            StrMess = StrMess & vbCrLf & "Name       :" & Me.txtName.Text
            StrMess = StrMess & vbCrLf & "Type       :" & Me.txtType.Text
            StrMess = StrMess & vbCrLf & "Message    :" & Me.txtMessage.Text
            StrMess = StrMess & vbCrLf & "Days       :" & Me.txtWorkingDays.Text
            MsgBox(StrMess)
            Me.btnAddNewTemplate.Content = "Add New Template"
            Me.RefreshList()


        End If

    End Sub

    Private Sub FillBookMarkList()
        Dim SQL As New StringBuilder
        With SQL
            .Append("SELECT Bookmark_ID, Bookmark_Text as Name, Bookmark_Desc as Description, Bookmark_Legacy")
            .Append(" FROM I_SL_Bookmarks")
            .Append(" WHERE (Bookmark_Legacy = 0)")
            .Append(" ORDER BY Bookmark_Text")
        End With
        Dim bookMarksList As DataTable = CommonDataFunctions.GetSQLDatatable(SQL.ToString())
        grdBookMarks.ItemsSource = bookMarksList
        grdBookMarks.Columns(0).IsVisible = False
        grdBookMarks.Columns(3).IsVisible = False
        grdBookMarks.Columns(1).Width = New GridLength(125)
        grdBookMarks.Columns(2).Width = New GridLength(190)
    End Sub

    Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCancel.Click
        Me.Cancel()
        ''''' fill the txtboxes if the grdTaskTemplate's row is selected
    End Sub

    Private Sub Cancel()
        Me.txtMessage.Text = String.Empty
        Me.txtName.Text = String.Empty
        Me.txtType.Text = String.Empty
        Me.txtWorkingDays.Text = String.Empty
        Me.grdBookMarks.IsEnabled = False
        Me.btnInsertBookmark.IsEnabled = False
        Me.btnCancel.IsEnabled = False
        Me.btnEditTemplate.IsEnabled = True
        If btnAddNewTemplate.Content.ToString.ToUpper = "SAVE" Then
            btnAddNewTemplate.Content = "Add New Template"
        End If
        If btnEditTemplate.Content.ToString.ToUpper = "SAVE" Then
            btnEditTemplate.Content = "Edit Template"
        End If
    End Sub

    Private Sub btnEditTemplate_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEditTemplate.Click
        Dim selectedTemplateRow As DataRow = Me.grdTemplates.SelectedItem, StrMess As New StringBuilder
        If Me.btnEditTemplate.Content.ToString.ToUpper = "EDIT TEMPLATE" Then
            If selectedTemplateRow Is Nothing Then
                MsgBox("Select the template to Edit")
                Exit Sub
            End If
            StrMess.Append("Updated Template details :" & vbCrLf)
            StrMess.Append("Task Template number " & selectedTemplateRow(0) & " (" & Me.txtName.Text & ") edited as follows" & vbCrLf & vbCrLf)
            Dim taskTemplateList As DataTable = Me.GetTaskTemplateList(selectedTemplateRow(0))
            Dim currentTaskTemplate As DataRow = taskTemplateList(0)
            Me.txtMessage.Text = currentTaskTemplate("Message")
            Me.txtName.Text = currentTaskTemplate("Name")
            Me.txtType.Text = currentTaskTemplate("Type")
            Me.txtWorkingDays.Text = currentTaskTemplate("Days")
            Me.btnInsertBookmark.IsEnabled = True
            Me.btnAddNewTemplate.IsEnabled = True
            Me.btnCancel.IsEnabled = True
            Me.btnDeleteTemplate.IsEnabled = True
            Me.btnEditTemplate.Content = "Save"
            Me.FillBookMarkList()
            Me.grdBookMarks.IsEnabled = True
            ''''''fill the grdBookMarks
        ElseIf Me.btnEditTemplate.Content.ToString.ToUpper = "SAVE" Then
            Dim StrSQL As String, Result As DataTable

            If Me.txtName.Text = String.Empty Then
                Call MsgBox("Name cannot be blank", , "Error")
                Me.txtName.Focus()
                Exit Sub
            End If

            If Len(Me.txtName.Text) > 50 Then
                Call MsgBox("Name too long (Max 50 chars)", , "Error")
                Me.txtName.Focus()
                Exit Sub
            End If

            If Me.txtType.Text = String.Empty Then
                Call MsgBox("Type cannot be blank", , "Error")
                Me.txtType.Focus()
                Exit Sub
            End If

            If Len(Me.txtType.Text) > 50 Then
                Call MsgBox("Type too long (Max 100 chars)", , "Error")
                Me.txtType.Focus()
                Exit Sub
            End If

            If Me.txtMessage.Text = String.Empty Then
                Call MsgBox("Message cannot be blank", , "Error")
                Me.txtMessage.Focus()
                Exit Sub
            End If

            If Me.txtWorkingDays.Text = String.Empty Then
                Call MsgBox("Working Days ahead cannot be blank", , "Error")
                Me.txtWorkingDays.Focus()
                Exit Sub
            End If

            If Not IsNumeric(Me.txtWorkingDays.Text) Then
                Call MsgBox("Invalid value for Working Days ahead", , "Error")
                Me.txtWorkingDays.Focus()
                Exit Sub
            End If

            If CInt(Me.txtWorkingDays.Text) < 0 Or CInt(Me.txtWorkingDays.Text) > 1200 Then
                Call MsgBox("Invalid value for Working Days ahead (0-1200 days)", , "Error")
                Me.txtWorkingDays.Focus()
                Exit Sub
            End If


            StrSQL = "Select TaskTemplate_ID from D_TaskTemplates"
            StrSQL = StrSQL & " Where TaskTemplate_Name = '" & Me.txtName.Text & "'"
            StrSQL = StrSQL & " And TaskTemplate_ID <> " & selectedTemplateRow(0)

            Result = CommonDataFunctions.GetSQLDatatable(StrSQL)
            If Result.Rows.Count > 0 Then
                Result.Dispose()
                Call MsgBox("There is already a template with that name", , "Error")
                Exit Sub
            End If


            StrSQL = String.Empty


            StrSQL = "Update D_TaskTemplates Set TaskTemplate_Name =' " & Me.txtName.Text.Trim & "', TaskTemplate_Type = '" & Me.txtType.Text & "',TaskTemplate_Message = '" & Me.txtMessage.Text & "', TaskTemplate_WorkingDays = " & CInt(Me.txtWorkingDays.Text)
            StrSQL = StrSQL & " Where TaskTemplate_ID = " & selectedTemplateRow(0)
            If CommonDataFunctions.ExecuteSQL(StrSQL) = True Then
                With StrMess
                    .Append(" Name : " & Me.txtName.Text & vbCrLf)
                    .Append(" Type : " & Me.txtType.Text & vbCrLf)
                    .Append(" No Of Working Days : " & Me.txtWorkingDays.Text & vbCrLf)
                    .Append(" Message : " & Me.txtMessage.Text & vbCrLf)
                End With
                RefreshList()
                Me.Cancel()
                MsgBox(StrMess.ToString(), MsgBoxStyle.Information, "Success")
            Else
                Me.btnEditTemplate.Content = "Edit Template"
                Exit Sub
            End If

        End If


    End Sub

    Private Sub btnInsertBookmark_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnInsertBookmark.Click
        Dim selectedBoorkMark As DataRow = grdBookMarks.SelectedItem
        If selectedBoorkMark Is Nothing Then
            Call MsgBox("Please select the bookmark to insert", , "Error")
            Exit Sub
        End If

        Dim StrMess As String

        If Convert.ToInt32(Me.Txt_CursorPosition.Text.ToString()) = 0 Then
            StrMess = " [" & selectedBoorkMark(1) & "] " & Me.txtMessage.Text
        Else
            StrMess = Microsoft.VisualBasic.Strings.Left(Me.txtMessage.Text, Convert.ToInt32(Me.Txt_CursorPosition.Text)) & " [" & selectedBoorkMark(1) & "] "
            StrMess = StrMess & Microsoft.VisualBasic.Strings.Right(Me.txtMessage.Text, Len(Me.txtMessage.Text) - Convert.ToInt32(Me.Txt_CursorPosition.Text))
        End If

        Me.txtMessage.Text = StrMess
    End Sub

    

    Private Sub txtMessage_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles txtMessage.KeyUp
        Me.Txt_CursorPosition.Text = Me.txtMessage.SelectionStart
    End Sub

    Private Sub txtMessage_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles txtMessage.MouseUp
        Me.Txt_CursorPosition.Text = Me.txtMessage.SelectionStart
    End Sub
End Class
